package com.bz.match.config;

import com.bz.match.MatchMessageSubscriber;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @author zhongyongbin
 * @since 2021/5/17
 */
@Configuration
public class MatchConfiguration {

    /**
     * 匹配消息主题
     *
     * @return 匹配消息主题
     */
    @Bean
    public ChannelTopic matchTopic() {
        return new ChannelTopic("topic:match");
    }

    /**
     * 匹配消息监听器
     *
     * @param matchMessageSubscriber 匹配消息订阅者
     * @return 匹配消息监听器
     */
    @Bean
    public MessageListenerAdapter matchMessageListener(MatchMessageSubscriber matchMessageSubscriber) {
        return new MessageListenerAdapter(matchMessageSubscriber);
    }

    /**
     * Redis 消息监听器容器
     *
     * @param redisConnectionFactory Redis 连接工厂
     * @param messageListenerAdapter 消息监听器
     * @param matchTopic             匹配消息主题
     * @return Redis 消息监听器容器
     */
    @Bean
    public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory,
                                                        @Qualifier("matchMessageListener") MessageListenerAdapter messageListenerAdapter,
                                                        @Qualifier("matchTopic") ChannelTopic matchTopic) {
        RedisMessageListenerContainer container
                = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(messageListenerAdapter, matchTopic);
        return container;
    }
}
